package Practice;

import java.util.Deque;
import java.util.LinkedList;

//使用队列模拟实现栈：两个队列相互配合，达成栈的效果  https://leetcode.cn/problems/implement-stack-using-queues/submissions/677206015/
class MyStackUseQueue {
    Deque<Integer> qu1;
    Deque<Integer> qu2;
    public MyStackUseQueue() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }
    
    public void push(int x) {
       if (qu1.isEmpty()) {
           qu2.offer(x);
       }else {
           qu1.offer(x);
       }
    }
    
    public int pop() {
        if (empty()) {
            return -1;
        }
        if (!qu2.isEmpty()) {
            int len = qu2.size()-1;
            for (int i = 0; i < len; i++) {
                qu1.offer(qu2.poll());
            }
            return qu2.poll();
        }else {
            int len = qu1.size()-1;
            for (int i = 0; i < len; i++) {
                qu2.offer(qu1.poll());
            }
            return qu1.poll();
        }
    }
    
    public int top() {
        if (empty()) {
            return -1;
        }
        int ret = 0;
        if (qu1.isEmpty()) {
            int len = qu2.size();
            for (int i = 0; i < len; i++){
                ret = qu2.peek();
                qu1.offer(qu2.poll());
            }
        }else {
            int len = qu1.size();
            for (int i = 0; i < len; i++) {
                ret = qu1.peek();
                qu2.offer(qu1.poll());
            }
        }
        return ret;
    }
    
    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty();
    }
}